package logic

import (
	"context"
	"fmt"
	"meituan/cache"
	"meituan/models"
	"meituan/pkg"

	"meituan/meituanrpc/internal/svc"
	"meituan/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *meituanrpc.RegisterRequest) (*meituanrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("该账户已经存在，请前去登录")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if result != in.CaptCha {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Mobile).Result()
	if s != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误，请重新登录")
	}

	user = models.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	models.DB.Debug().Create(&user)

	return &meituanrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
